<?php
namespace Lucanswu\Crypt;

class RSA
{
    private $private_key;
    private $public_key;
    public function __construct()
    {
        $this->private_key  = file_get_contents("./rsa/rsa_private_key.pem");
        $this->public_key   = file_get_contents("./rsa/rsa_public_key.pem");

    }


    /**
     * 公钥加密
     * @param unknown $data
     * @param unknown $padding
     */
    public function encrypt($data, $padding=OPENSSL_PKCS1_PADDING)
    {
        openssl_public_encrypt($data,$encrypted,$this->public_key, $padding);//公钥加密
        return base64_encode($encrypted);;
    }

    /**
     * 私钥解密
     * @param unknown $encrypted
     * @param unknown $padding
     */
    public function decrypt($encrypted, $padding=OPENSSL_PKCS1_PADDING)
    {
        openssl_private_decrypt(base64_decode($encrypted),$decrypted,$this->private_key,$padding);//私钥解密
        return $decrypted;
    }

    //处理特殊字符
    function safe_b64encode($string) {
        $data = base64_encode($string);
        $data = str_replace(array('+','/','='),array('-','_',''),$data);
        return $data;
    }

    //解析特殊字符
    function safe_b64decode($string) {
        $data = str_replace(array('-','_'),array('+','/'),$string);
        $mod4 = strlen($data) % 4;
        if ($mod4) {
            $data .= substr('====', $mod4);
        }
        return base64_decode($data);
    }


}